<template>
    <v-dialog v-model="dialogFormVisible" max-width="800px" persistent scrollable>
        <v-card class="elevation-10 pa-2">
            <v-card-title class="d-flex align-center">
                Edit
            </v-card-title>

            <v-card-text>
                <v-form ref="formRef" v-model="formValid">
                    <v-row>
                        <v-col cols="12" md="6">
                            <v-checkbox v-model="form.isEditable" label="仅管理员修改" variant="outlined" density="compact"
                                :rules="rules.isEditable" required hide-details="auto" :true-value="2"
                                v-if="$perms('system_tenantconfig_import')" :false-value="1" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.name" label="配置名称" variant="outlined" density="compact"
                                :rules="rules.name" required hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.value" label="配置值" variant="outlined" density="compact"
                                :rules="rules.value" required hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.remarks" label="备注" variant="outlined" density="compact"
                                :rules="rules.remarks" required hide-details="auto" />
                        </v-col>
                    </v-row>
                </v-form>
            </v-card-text>

            <v-card-actions>
                <v-spacer />
                <v-btn color="grey-darken-1" variant="text" @click="close">
                    Cancel
                </v-btn>
                <v-btn color="primary" variant="text" :loading="saving" @click="save">
                    Confirm
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue';
import {
    doInsert,
    doUpdate,
    type SysTenantConfigModel,
    type ApiResponse
} from '@/api/system/tenantconfig/SysTenantConfigManagementApi';
import { isNull } from '@/utils/validate';
import { formateDate } from '@/utils/format';
import { validatorRule } from '@/utils/validateRule';
import { getDictListSync } from '@/utils/dict';
import { useMessage } from '@/composables/useMessage';

const { success: showSuccess, error: showError } = useMessage();

// 基础数据
const dialogFormVisible = ref(false);
const title = ref('');
const formValid = ref(false);
const formRef = ref();
const saving = ref(false);
const defaultFrom: SysTenantConfigModel = {
    isEditable: 0,
    name: '',
    value: '',
    remarks: '',
    createTime: '',
    createBy: '',
}

// 表单数据
const form = reactive<Partial<SysTenantConfigModel>>(defaultFrom);

// 字典数据
const dict = reactive({
});

// 验证规则
const rules = {
    isEditable: [
        (v: any) => !!v || '仅管理员修改不能为空',
    ],
    name: [
        (v: any) => !!v || '配置名称不能为空',
    ],
    value: [
        (v: any) => !!v || '配置值不能为空',
    ],
    remarks: [
        (v: any) => !!v || '备注不能为空',
    ],
    createTime: [
        (v: any) => !!v || '创建时间不能为空',
    ],
    createBy: [
        (v: any) => !!v || '创建者不能为空',
    ],
};

// 事件发射
const emit = defineEmits<{
    fetchData: [];
}>();

// 显示编辑对话框
function showEdit(row?: SysTenantConfigModel) {
    if (!row) {
        title.value = '添加租户配置';
        // 重置表单为默认值
        Object.assign(form, defaultFrom);
    } else {
        title.value = '编辑租户配置';
        // 复制行数据到表单，处理日期格式
        const formData = { ...row };


        Object.assign(form, formData);
    }

    dialogFormVisible.value = true;
}

// 关闭对话框
function close() {
    dialogFormVisible.value = false;
    nextTick(() => {
        if (formRef.value) {
            formRef.value.reset();
        }
        // 重置表单数据
        Object.assign(form, defaultFrom);
    });
}

// 保存
async function save() {
    if (!formRef.value) return;

    try {
        const { valid } = await formRef.value.validate();
        if (!valid) return;

        saving.value = true;

        // 处理表单数据
        const submitData = { ...form } as SysTenantConfigModel;
        handlerFormData(submitData);

        let response: ApiResponse<SysTenantConfigModel>;

        // 编辑模式
        if (!isNull(submitData.id)) {
            let { msg } = await doUpdate(submitData);
            showSuccess(msg || 'update success');
        } else {
            // 新增模式
            let { msg } = await doInsert(submitData);
            showSuccess(msg || 'add success');
        }

        // 通知父组件刷新数据
        emit('fetchData');
        close();
    } catch (error) {
        console.error('save failed:', error);
        showError('save failed');
    } finally {
        saving.value = false;
    }
}

// 处理表单数据
function handlerFormData(formData: any) {
    if (!isNull(formData)) {
        for (const key in formData) {
            // 对于时间类进行处理
            if (Object.prototype.toString.call(formData[key]) === '[object Date]') {
                formData[key] = formateDate(formData[key], 'yyyy-MM-dd hh:mm:ss');
            }
            // 处理datetime-local格式
            else if (typeof formData[key] === 'string' && formData[key].includes('T')) {
                formData[key] = formData[key].replace('T', ' ') + ':00';
            }
        }
    }
}

// 初始化字典数据
function initDict() {
}

// 暴露方法
defineExpose({
    showEdit,
});

// 生命周期
onMounted(() => {
    initDict();
});
</script>

<style lang="scss" scoped>
:deep(.v-dialog) {
    .v-card-title {
        background-color: rgb(var(--v-theme-primary));
        color: white;
    }
}
</style>